layui.define(['message'], function (exports) {
    var Http = function () {}

    Http.prototype.cache = function (url, data, success, failure) {
        // 如果第二个参数为函数，则移位
        if (jQuery.isFunction(data)) {
            failure = success;
            success = data;
            data = undefined;
        }

        // 尝试从缓存中获取已经加载的数据 
        try {
            var cache = sessionStorage.getItem('cache-' + url);

            // 判断缓存值是否为空 & 如果不为空就进行反序列化
            if (cache && cache !== 'null' && cache !== 'undefined') {
                var cacheData = JSON.parse(cache);

                // 验证是否存在回调函数 & 缓存数据是否有效
                if (cacheData && jQuery.isFunction(success)) {
                    return success.call(this, cacheData);
                }
            }
        } catch (e) {
            console.error('request cache data is failure!', e)
        }

        return this.ajax({
            url: url,
            data: data,
            method: 'GET',
            failure: failure,
            loading: layui.message.loading(),
            success: function (result) {
                // 将请求结果存入缓存中
                sessionStorage['cache-' + url] = JSON.stringify(result);

                // 回调成功接口
                if (success && jQuery.isFunction(success)) {
                    success.call(this, result);
                }
            },
        });
    }

    Http.prototype.get = function (url, data, success, failure) {
        // 如果第二个参数为函数，则移位
        if (jQuery.isFunction(data)) {
            failure = success;
            success = data;
            data = undefined;
        }

        return this.ajax({
            url: url,
            data: data,
            method: 'GET',
            success: success,
            failure: failure,
            loading: layui.message.loading(),
        });
    }

    Http.prototype.post = function (url, data, success, failure) {
        // 如果第二个参数为函数，则移位
        if (jQuery.isFunction(data)) {
            failure = success;
            success = data;
            data = undefined;
        }

        return this.ajax({
            url: url,
            data: data,
            method: 'POST',
            success: success,
            failure: failure,
            loading: layui.message.loading(),
        });
    }

    Http.prototype.json = function (url, data, success, failure) {
        // 如果第二个参数为函数，则移位
        if (jQuery.isFunction(data)) {
            failure = success;
            success = data;
            data = undefined;
        }

        return this.ajax({
            url: url,
            method: 'POST',
            success: success,
            failure: failure,
            data: JSON.stringify(data || {}),
            loading: layui.message.loading(),
            type: 'application/json; charset=utf-8',
        });
    }

    /** 执行ajax请求 */
    Http.prototype.ajax = function (options) {
        return jQuery.ajax({
            traditional: true,
            url: options.url,
            data: options.data,
            type: options.method,
            contentType: options.type,
            success: function (response) {
                if (response && response.code === 'SUCCESS') {
                    if (jQuery.isFunction(options.success)) {
                        options.success.call(this, response);
                    } else {
                        console.log(`Request ${options.url}:`, response);
                    }
                } else {
                    layui.message.failure(response.message);

                    // 回调错误接口
                    if (jQuery.isFunction(options.failure)) {
                        options.failure.call(this, response);
                    }
                }
            },
            error: function (err) {
                layui.message.failure(err.statusText || "连接异常");

                // 回调错误接口
                if (jQuery.isFunction(options.failure)) {
                    options.failure.call(this, err);
                }
            },
            complete: function () {
                layui.message.close(options.loading);
            }
        });
    }

    /** 序列化form表单 */
    Http.prototype.serializeJson = function (elem) {
        var answer = {};

        $.each($(elem).serializeArray(), function (index, item) {
            var lastValue = answer[item.name] || false;

            if (!lastValue && Array.isArray(lastValue)) {
                answer[item.name] = lastValue.concat(item.value);
            } else if (!lastValue) {
                answer[item.name] = [lastValue, item.value];
            } else {
                answer[item.name] = item.value;
            }
        });

        return answer;
    }

    exports('http', new Http());
});